package com.ppt.android.base

import android.content.res.Configuration
import android.content.res.Resources
import android.os.Bundle
import android.util.Log
import androidx.lifecycle.ViewModelProvider
import androidx.viewbinding.ViewBinding
import com.ppt.android.activity.vm.DefaultViewModel
import com.ppt.android.base.mvvm.v.BaseFrameActivity
import com.ppt.android.base.mvvm.vm.BaseViewModel
import com.ppt.android.base.utils.ActivityStackManager
import com.ppt.android.base.utils.AndroidBugFixUtils
import com.ppt.android.base.utils.BarUtils
import com.ppt.android.base.utils.LogUtils
import com.ppt.android.base.utils.SpUtils
import com.ppt.android.utils.AnalyticsUtil

/**
 * Activity基类
 *
 * @author ZouJiaCai
 * @since 8/27/20
 */
abstract class BaseActivity<VB : ViewBinding, VM : BaseViewModel> : BaseFrameActivity<VB, VM>() {


    open val defaultViewModel:DefaultViewModel? by lazy {
        if (this is SharedViewModelUser) ViewModelProvider(this)[DefaultViewModel::class.java]
        else null
    }

    private var isPageTracked = false//是否统计

    // 标记接口
    interface SharedViewModelUser

    /**
     * 设置状态栏
     * 子类需要自定义时重写该方法即可
     * @return Unit
     */
    override fun setStatusBar() {
        BarUtils.transparentStatusBar(this)
        BarUtils.setStatusBarLightMode(this, true)
    }

    val screenWidthDp: Int
        get() {
            val displayMetrics = Resources.getSystem().displayMetrics
            return (displayMetrics.widthPixels / displayMetrics.density).toInt()
        }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val count = SpUtils.getInt(SpUtils.BACK_COUNT,0)
        if(count!=null){
            SpUtils.put(SpUtils.BACK_COUNT, count+1)
        }
    }

    override fun onResume() {
        super.onResume()
        if(!isPageTracked){
            AnalyticsUtil.logScreenView(this::class.java.simpleName, null)
            isPageTracked = true
            Log.d("test_home",this::class.java.simpleName)
        }
        LogUtils.d("ActivityLifecycle", "ActivityStack: ${ActivityStackManager.activityStack}")
    }

    override fun onDestroy() {
        super.onDestroy()
        // 解决某些特定机型会触发的Android本身的Bug
        AndroidBugFixUtils().fixSoftInputLeaks(this)
    }





//----------------------       3          ----------------
    override fun getResources(): Resources {
        val resources = super.getResources()
        val configuration = Configuration()
        if (configuration.fontScale != 1f) {
//            System.out.println("setFontScale初始化前: " + configuration.fontScale)
            configuration.setToDefaults()
//            System.out.println("setFontScale初始化后: " + configuration.fontScale)
            resources.updateConfiguration(configuration, resources.displayMetrics)
        }
        return resources
    }




}